﻿using DatabaseUpdater;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace DatabaseUpdaterMgr
{
    public class Updater : InterfaceUpdateInfo
    {
        private readonly string _sourceConnectionString;//连接中间库的连接字符串
        private readonly string _query; //查询中间库的SQL语句
        public Updater(string sourceConnectionString, string query)
        {
            _sourceConnectionString = sourceConnectionString;
            _query = query;
        }
        /// <summary>
        /// 失败信息处理
        /// </summary>
        /// <param name="data"></param>
        /// <param name="memo"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void MessageProcessing(UpdateInfo data, string memo)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 读取数据
        /// </summary>
        /// <returns></returns>
        public List<UpdateInfo> GetDataBaseInfo()
        {
            using (var sourceConnection = new SqlConnection(_sourceConnectionString))
            {
                sourceConnection.Open();
                using (var command = sourceConnection.CreateCommand())
                {
                    List<UpdateInfo> updateInfos = new List<UpdateInfo>();
                    command.CommandText = _query;
                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            // 读取数据
                            updateInfos.Add(new UpdateInfo { });
                        }
                    }
                    return updateInfos;
                }
            }
        }
        /// <summary>
        /// // 更新
        /// </summary>
        /// <param name="data"></param>
        public void UpdateDataBaseInfo(UpdateInfo data)
        {
        }
        public void UpdateDataBase()
        {
            TransactionOptions opt = new TransactionOptions();
            opt.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
            using (var tr = new TransactionScope(TransactionScopeOption.Required, opt))
            {
                Updater updater = new Updater("", "");
                // 读取数据
                var updateInfoList = updater.GetDataBaseInfo();
                foreach (var updateInfo in updateInfoList)
                {
                    try
                    {
                        //更新
                        updater.UpdateDataBaseInfo(updateInfo);
                    }
                    catch (Exception ex)
                    {
                        MessageProcessing(updateInfo, ex.Message);
                    }
                }
                tr.Complete();
            }
        }

    }
}
